package com.sjzl.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sjzl.entity.Friend;
import com.sjzl.entity.User;
import com.sjzl.service.FriendService;
import com.sjzl.service.UserService;

@Component("friendServiceImpl")
public class FriendServiceImpl extends ServiceImpl<Friend> implements FriendService{
	
	@Resource(name="userServiceImpl")
	private UserService userService;

	@Override
	public void create(Friend friend) {}

	@Transactional
	public boolean create(User user) {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession httpSession = request.getSession();
		User sessionUser = (User) httpSession.getAttribute("sessionUser");
		User dbUser = userService.get(User.class, sessionUser.getId());
		List<Friend> friends = dbUser.getFriends();
		for(Friend f : friends){
			if(f.getFusername().equals(user.getAccount())){
				return false;
			}
		}
		if(user.getAccount().equals(sessionUser.getAccount())){
			return false;
		}
		
		Friend f = new Friend();
		f.setDateCreated(new Date());
		f.setFusername(user.getAccount());
		f.setUser(sessionUser);
		f.setMyselfUser(user);
		f.setHeadImageSrc(user.getHeadImageSrc());
		this.getDao().save(f);
		return true;
	}
	
}
